package pl.plesken.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedList;

import noNamespace.GenreType;
import noNamespace.GenresDocument;
import noNamespace.GenresType;

import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlOptions;

public class GenresXML {
	
	LinkedList<String> row = new LinkedList<String>();
	LinkedList<String> save = new LinkedList<String>();
	StringBuffer str = new StringBuffer();
	StringBuffer xml = new StringBuffer();
	

	public LinkedList<String> getRow() {
		return row;
	}

	public void setRow(LinkedList<String> row) {
		this.row = row;
	}

	public LinkedList<String> getSave() {
		return save;
	}

	public void setSave(LinkedList<String> save) {
		this.save = save;
	}


	public void getGenreValues() {
		try {
			File xmlFile = new File("genres.xml");
			GenresDocument load = GenresDocument.Factory.parse(xmlFile);
			
			GenreType[] genre = load.getGenres().getGenreArray();
			
			row.clear();
			
			for (int x = 0; x < genre.length; x++) {
				if (!genre[x].getName().equals("")) {
					str.append(genre[x].getName());
				} else {
					str.append("empty");
				}
				
				for (int a = 0; a < genre[x].getSubgenreArray().length; a++) {
					if (!genre[x].getSubgenreArray(a).equals("")) {
						str.append(";" + genre[x].getSubgenreArray(a).toString());
					} else {
						str.append(";empty");
					}
				}
				
				String val = str.toString();
				row.add(val);
				str.setLength(0);
			}
			
		} catch(XmlException e) {
			System.err.println(e);
		} catch(IOException e) {
			System.err.println(e);
		} catch(NullPointerException e) {
		}
	}
	
	public void saveGenreValues() {
		try {
			GenresDocument genres = GenresDocument.Factory.newInstance();
			GenresType genresType = GenresType.Factory.newInstance();
			
			for (int i = 0; i < save.size(); i++) {
				String[] tab = save.get(i).split(";");
				genresType.addNewGenre();
				GenreType genreType = GenreType.Factory.newInstance();
				genreType.setName(tab[0]);
				
				for (int s = 1; s < tab.length; s++) {
					genreType.addNewSubgenre().setStringValue(tab[s]);
				}
				
				genresType.setGenreArray(i, genreType);
			}
			
			genres.setGenres(genresType);
			
			save.clear();
			
			File out = new File("genres.xml");
			OutputStream os = new FileOutputStream(out);
	
			XmlOptions options = new XmlOptions();
			options.setSavePrettyPrint();
			genres.save(out, options);
			os.flush();
			
		} catch(IOException e) {
			System.err.println(e);
		} catch(NullPointerException e) {
		}
	}
	
}
